home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5687 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.4 KB

  1. Path: news.ccs.queensu.ca!news
  2. From: Wintermute <3mal5@qlink.queensu.ca>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Trouble w/ random numbers...please help
  5. Date: 6 Feb 1996 05:55:11 GMT
  6. Organization: System Infinity
  7. Message-ID: <4f6qfv$c4m@knot.queensu.ca>
  8. References: <4f0g5u$879@ns.campus.mci.net> <DMBIHq.L3u@news.arco.com>
  9. NNTP-Posting-Host: free1-slip204.tele.queensu.ca
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 1.1N (Macintosh; I; 68K)
  14. X-URL: news:DMBIHq.L3u@news.arco.com
  15.  
  16. Brian Leach <lasbfl> wrote:
  17. >Daniel Cotter <cotter@www.cns.uky.edu> wrote:
  18. >>I'm trying to write a program that will generate a set of
  19. >>random numbers between 3 and 18. I have several problems with
  20. >>this program.
  21. >>1. C++ always generates same number(346)
  22. >>2. I don't know how to give a range. I've tried 3-18, but
  23. >>   it thinks I mean to subtract(3-18=15)
  24. >>3. When it does work, it's always the same number
  25.  
  26. 1.  Brian was right, seed the random number generator.  These numbers 
  27. are not really random, but are statistically indistinguishable from 
  28. random numbers (ie, for most uses they are adequate as random numbers).  
  29. The random number generator applies its algorithm to this seed to 
  30. generate its sequence of pseudorandom numbers.
  31.  
  32. 2.  Typically random number generators return a real number between 0.0 
  33. and 1.0.  You want a random number between 3 and 18, a range of 15.
  34.  
  35. Basically, you want to scale your random number to the same range, by 
  36. multiplying it by 16.  So now you have a real number between 0.0 and 
  37. 16.0.  Next, translate it to the same 'location' by adding 3.  Now you 
  38. have a real number between 3.0 and 19.0.  Finally, take the floor of 
  39. this number (the part before the decimal) to get a natural number 
  40. between 3 and 18 (watch out for the 19.0 case, though, that you don't 
  41. get 19!).
  42.  
  43. The reason you want to scale by an extra number and use floor instead of 
  44. just rounding is because with rounding, your lowest and highest values 
  45. (3 and 18) will occur only half as likely as all the others (4, 5, ..., 
  46. 17).
  47.  
  48. Of course, this is just the logic behind it all.  This normally can be 
  49. done all in one simple, obscure line of code.
  50.  
  51. --
  52. Wintermute  <3mal5@qlink.queensu.ca>  <http://qlink.queensu.ca/~3mal5/>
  53.  
  54. "If I really knew how to write, I could write something that someone
  55. could read and it would kill them."  -  william s. burroughs
  56.  
  57.  
  58.